package com.mot.st.network

import android.util.Log
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.TypeAdapterFactory
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException


/**
 * 自定义TypeAdapter ,null对象将被解析成空字符串
 */
class NullStringToEmptyAdapterFactory<T> : TypeAdapterFactory {
    override fun <T> create(gson: Gson?, type: TypeToken<T>): TypeAdapter<T>? {
        val rawType = type.rawType as Class<T>
        return if (rawType != String::class.java) {
            null
        } else StringNullAdapter() as TypeAdapter<T>
    }
}


class StringNullAdapter : TypeAdapter<String?>() {
    @Throws(IOException::class)
    override fun read(reader: JsonReader): String? {
        // TODO Auto-generated method stub
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull()

            return ""
        }
        return reader.nextString()
    }

    @Throws(IOException::class)
    override fun write(writer: JsonWriter, value: String?) {
        // TODO Auto-generated method stub
        if (value == null) {
            writer.nullValue()
            return
        }
        writer.value(value)
    }
}


//class NullListToEmptyAdapterFactory<T> : TypeAdapterFactory {
//    override fun <T> create(gson: Gson?, type: TypeToken<T>): TypeAdapter<T>? {
//        val rawType = type.getRawType() as Class<T>
//        return if (rawType != List::class.java) {
//            null
//        } else ListNullAdapter<T>() as TypeAdapter<T>
//    }
//}
//
//class ListNullAdapter<T> : TypeAdapter<List<T>?>() {
//    @Throws(IOException::class)
//    override fun read(reader: JsonReader): List<T>? {
//        if (reader.peek() == JsonToken.NULL) {
//            reader.nextNull()
//            return emptyList<T>()
//        }
//    }
//
//    @Throws(IOException::class)
//    override fun write(writer: JsonWriter, value: List<T>?) {
//        if (value == null) {
//            writer.nullValue()
//            return
//        }
//        writer.value("")
//    }
//}